import React, {useEffect, useState} from "react";
import {Button, Col, Form, Input, message, Modal, Row, Select} from "antd";
import type {Result} from "@/types/result";
import applicationRecordApi from "@/api/applicationRecordApi.ts";
import {ApplicationRecord} from "@/types/resp/applicationRecord";
import EnterpriseSelector from "@/pages/enterprise/EnterpriseSelector.tsx";
import JobDescriptionSelector from "@/pages/jobDescription/JobDescriptionSelector.tsx";
import CandidateSelector from "@/pages/candidate/CandidateSelector.tsx";

interface ApplicationRecordAddProps {
  visible: boolean;
  id: number;
  onCloseApplicationRecordAdd: () => void;
}

const ApplicationRecordAdd: React.FC<ApplicationRecordAddProps> = ({visible, id, onCloseApplicationRecordAdd}) => {

  const [form] = Form.useForm<ApplicationRecord>();
  const [messageApi, messageContextHolder] = message.useMessage();

  const rules = {
    enterpriseName: [
      { required: true, message: '请输入企业名称' }
    ],
    jobDescriptionName: [
      { required: true, message: '请输入招聘岗位名称' }
    ],
    candidateName: [
      { required: true, message: '请输入应聘者姓名' }
    ],
    status: [
      { required: true, message: '请输入状态' }
    ],
  };

  let applicationRecordForm: Partial<ApplicationRecord> = {}

  const [title, setTitle] = useState('新增应聘申请');

  useEffect(() => {
    if (!visible) {
      return
    }
    if (id) {
      setTitle('编辑应聘申请')
      initApplicationRecordFormById(id)
    } else {
      setTitle('新增应聘申请')
      form.resetFields();
    }
  }, [visible]);

  const initApplicationRecordFormById = async (id: number) => {
    const resp: Result<ApplicationRecord> = await applicationRecordApi.findById(id)
    if (resp && resp.code === 1 && resp.data) {
      applicationRecordForm = resp.data
      form.setFieldsValue(resp.data);
    }
  }

  const onSave = async () => {
    try {
      await form.validateFields()

      let applicationRecord2Save:ApplicationRecord = form.getFieldsValue()
      if (id) {
        applicationRecord2Save = Object.assign(applicationRecordForm, applicationRecord2Save)
      }
      const resp: Result<void> = await applicationRecordApi.save(applicationRecord2Save);
      if (!resp || resp.code !== 1) {
        messageApi.error('保存失败:' + (resp.msg ? resp.msg : '未知异常'));
        return
      }
      messageApi.success('保存成功');
      onBack()
    } catch (error) {
      console.error('There was an error submitting the form!', error);
    }
  };

  const onReset = () => {
    setTitle('新增应聘申请')
    form.resetFields();
  };
  
  const [enterpriseSelectorVisible, setEnterpriseSelectorVisible] = useState(false);
  const findEnterprise = () => {
    setEnterpriseSelectorVisible(true);
  }
  const handleEnterpriseSelected = (selectedEnterprise: { enterpriseId?: number; enterpriseName?: string; }) => {
    setEnterpriseSelectorVisible(false)
    if (selectedEnterprise && 'enterpriseId' in selectedEnterprise) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      enterpriseId: selectedEnterprise['enterpriseId'],
      enterpriseName: selectedEnterprise['enterpriseName'],
      }));
    }
  };
  const handleCloseEnterpriseSelector = () => {
    setEnterpriseSelectorVisible(false)
  };
  const [jobDescriptionSelectorVisible, setJobDescriptionSelectorVisible] = useState(false);
  const findJobDescription = () => {
    setJobDescriptionSelectorVisible(true);
  }
  const handleJobDescriptionSelected = (selectedJobDescription: { jobDescriptionId?: number; jobDescriptionName?: string; }) => {
    setJobDescriptionSelectorVisible(false)
    if (selectedJobDescription && 'jobDescriptionId' in selectedJobDescription) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      jobDescriptionId: selectedJobDescription['jobDescriptionId'],
      jobDescriptionName: selectedJobDescription['jobDescriptionName'],
      }));
    }
  };
  const handleCloseJobDescriptionSelector = () => {
    setJobDescriptionSelectorVisible(false)
  };
  const [candidateSelectorVisible, setCandidateSelectorVisible] = useState(false);
  const findCandidate = () => {
    setCandidateSelectorVisible(true);
  }
  const handleCandidateSelected = (selectedCandidate: { candidateId?: number; candidateName?: string; }) => {
    setCandidateSelectorVisible(false)
    if (selectedCandidate && 'candidateId' in selectedCandidate) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      candidateId: selectedCandidate['candidateId'],
      candidateName: selectedCandidate['candidateName'],
      }));
    }
  };
  const handleCloseCandidateSelector = () => {
    setCandidateSelectorVisible(false)
  };

  const onBack = () => {
    onCloseApplicationRecordAdd()
  };

  const addFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onSave}>保存</Button>
      <Button onClick={onReset} style={{marginLeft: 'var(--button-margin-left)'}}>重置</Button>
      <Button type="primary" onClick={onBack} style={{marginLeft: 'var(--button-margin-left)'}}>关闭</Button>
    </div>
  );

  return (
    <Modal title={title} open={visible} onCancel={onCloseApplicationRecordAdd} width={'var(--modal-width)'}
        footer={addFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      {messageContextHolder}
      <Form form={form} name="applicationRecordForm" labelCol={{span: 6}}>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="enterpriseName" label="企业名称"  rules={rules.enterpriseName}>
              <Input.Search placeholder="请选择企业名称" onSearch={findEnterprise} readOnly={true} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="jobDescriptionName" label="招聘岗位名称"  rules={rules.jobDescriptionName}>
              <Input.Search placeholder="请选择招聘岗位名称" onSearch={findJobDescription} readOnly={true} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="candidateName" label="应聘者姓名"  rules={rules.candidateName}>
              <Input.Search placeholder="请选择应聘者姓名" onSearch={findCandidate} readOnly={true} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="status" label="状态" rules={rules.status}>
              <Select placeholder="请选择状态" options={[
                { value: 10, label: <span>申请</span> },
                { value: 20, label: <span>面试邀约</span> },
                { value: 30, label: <span>录用</span> },
                { value: 90, label: <span>拒绝</span> }
              ]} />
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <EnterpriseSelector visible={enterpriseSelectorVisible} onEnterpriseSelected={handleEnterpriseSelected} onCloseEnterpriseSelector={handleCloseEnterpriseSelector} />
      <JobDescriptionSelector visible={jobDescriptionSelectorVisible} onJobDescriptionSelected={handleJobDescriptionSelected} onCloseJobDescriptionSelector={handleCloseJobDescriptionSelector} />
      <CandidateSelector visible={candidateSelectorVisible} onCandidateSelected={handleCandidateSelected} onCloseCandidateSelector={handleCloseCandidateSelector} />
    </Modal>
  )
}

export default ApplicationRecordAdd;
